package org.ccheng.gui.console;

import cn.hutool.core.date.DateUtil;
import de.felixroske.jfxsupport.FXMLController;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.scene.control.TextArea;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import lombok.SneakyThrows;
import org.ccheng.common.io.LoopedStreams;

import java.io.*;
import java.net.URL;
import java.util.ResourceBundle;

@FXMLController
public class ConsoleCtrl implements Initializable {

    @FXML
    private TextArea consoleText;

    @SneakyThrows
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        consoleText.setEditable(false);

        final LoopedStreams ls = new LoopedStreams();
        // 重定向System.out和System.err
        PrintStream ps = new PrintStream(ls.getOutputStream());
        System.setOut(ps);
        System.setErr(ps);

        startConsoleReaderThread(ls.getInputStream());
    }

    private void startConsoleReaderThread(InputStream inStream) {
        final BufferedReader br = new BufferedReader(new InputStreamReader(inStream));
        new Thread(() -> {
            StringBuffer sb = new StringBuffer();
            try {
                String s;
                //Document doc = getDocument;
                while ((s = br.readLine()) != null) {
                    boolean caretAtEnd = false;
                    sb.setLength(0);

                    String text = sb.append(DateUtil.now()).append(" - ").append(s).append('\n').toString();

                    Platform.runLater(() -> consoleText.appendText(text));
                }
            } catch (IOException e) {
                System.out.println("线程炸裂");
                System.exit(1);
            }
        }).start();
    } // startConsoleReaderThread()

}
